#!/usr/bin/perl -w

use strict;
use warnings;
use Time::HiRes qw(sleep);
use lib '/home/myuser/selenium-remote-control-1.0.1/selenium-perl-client-driver-1.0.1/lib';
use Test::WWW::Selenium;
use DBI;

my ($sec,$min,$hour,$mday,$mon,$year,$wday,
    $yday,$isdst)=localtime(time);
my $date = sprintf "%4d-%02d-%02d", $year+1900,$mon+1,$mday;
my $time = sprintf "%02d:%02d:%02d", $hour,$min,$sec;
my($status1, $time1) = (0, 0);
my($status2, $time2) = (0, 0);;
my($status3, $time3) = (0, 0);;
my($status4, $time4) = (0, 0);;

# Selenium setup, using Firefox as is
my $sel = Test::WWW::Selenium->new( host => "localhost",
                                    port => 4441,
                                    browser => "*firefox",
                                    browser_url => "http://www.google.com/" );

# Dependent on how many tests to run mody these rows
($status1, $time1) = &test1();
if (!$status1){ ($status2, $time2) = &test1();}
if (!$status1 && !$status2){ ($status3, $time3) = &test1(); }
if (!$status1 && !$status2 && !$status3){($status4, $time4) = &test1(); }

# Save results to database
&insert_row($date, $time, $status1, $time1,  $status2, $time2,  $status3, $time3,  $status4, $time4);
$sel->DESTROY;


#
# This is the actual test function write one of these for each test case.
# This one makes a search on google and verifies by title row
#
sub test1 {
    my $start;
    my $elapsed = 0;

    $sel->open("/");
    $sel->wait_for_page_to_load("30000");
    if ("Google" ne $sel->get_title()) {
	return (1, 0);
    }

    $sel->type("q", "selenium rc");
    $start = [ Time::HiRes::gettimeofday( ) ];
    $sel->click("btnG");
    $sel->wait_for_page_to_load("30000");
    if ("selenium rc - Google-search" ne $sel->get_title()) {
        return (2, int(Time::HiRes::tv_interval($start)*1000));
    }
    $elapsed = int(Time::HiRes::tv_interval($start)*1000);
        
    if (! $sel->is_text_present("Results * for selenium rc")) {
	$result = 3;
    }
    print "Elapsed time(ms): $elapsed\n";
    return (0, $elapsed);
}

#
# Saves to database
#
sub insert_row {
    my $p1 = shift;
    my $p2 = shift;
    my $p3 = shift;
    my $p4 = shift;
    my $p5 = shift;
    my $p6 = shift;
    my $p7 = shift;
    my $p8 = shift;
    my $p9 = shift;
    my $p10 = shift;

    my $username = 'metria';
    my $password = '';
    my $database = 'metria';
    my $hostname = 'localhost';
    
    my $dbh = DBI->connect("dbi:mysql:database=$database;" . 
			"host=$hostname;port=3306", $username, $password);
    
    my $SQL= "insert into metria_statistics (date, time, status1, time1, status2, time2, status3, time3, status4, time4)" .
	" values('$p1', '$p2', $p3, $p4, $p5, $p6, $p7, $p8, $p9, $p10)";

    my $InsertRecord = $dbh->do($SQL);
    
    if(! $InsertRecord){
	print "SQL: Failure $DBI::errstr";
    }
}
